<template>
  <el-tree
    ref="tree"
    show-checkbox
    :data="data"
    :props="treeProps"
    @check-change="change"
    node-key="id"
    >
  </el-tree>
</template>

<script>
export default {
  data() {
    return {
      treeProps: {
        children: "childList",
        label: "label"
      }
      //treeProductLinData: []
    };
  },
  model: {
    prop: "checkedNodes",
    event: "change"
  },
  props: {
    checkedNodes: {
      type: [String, Array]
      // default: function () {
      //   return []
      // }
    },
    data: {
      type: Array,
      required: true,
      default(){
        return []
      }
    },
    defaultCheckedKeys: {
      type: Array
    }
  },
  created() {
    // TODO: remote load
    //this.treeProductLinData = mockProductLineData;
  },
  mounted() {
  },
  watch: {
    data() {
      var arr = [];
      this.data.forEach(obj => {
        if (obj.selected) {
          arr.push(obj.id);
        }
        obj.childList.forEach(obj => {
            if (obj.selected) {
              arr.push(obj.id);
            }
          });
      });
      // console.log(arr)
      if (arr.length>0) {
        this.$refs.tree.setCheckedKeys(arr,true);
      }
      return arr;
    }
  },
  methods: {
    change(data, arg1, arg2) {
      let leafOnly = true;
      // this.$emit('change', this.$refs.tree.getCheckedNodes(leafOnly))
      let checkArr = this.$refs.tree.getCheckedKeys(leafOnly);
      debugger
      this.data.forEach(obj => {
        obj.childList.forEach(childObj => {
          childObj.selected=false;
          checkArr.forEach(id => {
            if (id == childObj.id) {
              childObj.selected = true;
            }
          });
        });
      });
      debugger;
      this.$emit("change", this.data);
    }
  }
};
</script>

<style scoped>
.el-tree >>> .el-checkbox__input.is-disabled {
  display: none;
}
</style>
